package com.itany.shop.dao.impl;

import com.itany.shop.dao.OrderDao;
import com.itany.shop.entity.Item;
import com.itany.shop.entity.Order;
import com.itany.shop.entity.Product;
import com.itany.shop.entity.User;
import com.itany.shop.exception.DataAccessException;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.util.JDBCTemplate;
import com.itany.shop.util.JDBCUtil;
import com.itany.shop.util.RowMapper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 石小俊
 */
public class OrderDaoImpl implements OrderDao {

    private JDBCTemplate jdbcTemplate = (JDBCTemplate) ObjectFactory.getObject("jdbc");

    @Override
    public Integer insertReturnPrimaryKey(Order order) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Integer id = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" insert into ")
                    .append(" t_order(no,price,user_id)")
                    .append(" values(?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
            ps.setString(1, order.getNo());
            ps.setDouble(2, order.getPrice());
            ps.setInt(3, order.getUser().getId());
            ps.executeUpdate();
            // 获取返回的主键
            rs = ps.getGeneratedKeys();
            while (rs.next()) {
                id = rs.getInt(1);
            }
        } catch (SQLException e) {
            throw new DataAccessException("数据访问异常");
        }
        return id;
    }

    @Override
    public List<Order> selectByUserId(Integer userId) {
        String sql = new StringBuffer()
                .append(" select id,no,price,user_id ")
                .append(" from t_order")
                .append(" where user_id = ? ")
                .toString();
        List<Order> orders = jdbcTemplate.query(sql, new RowMapper() {
            @Override
            public Object mapRow(ResultSet rs) throws Exception {
                Order order = new Order();
                order.setId(rs.getInt("id"));
                order.setNo(rs.getString("no"));
                order.setPrice(rs.getDouble("price"));

                User user = new User();
                user.setId(rs.getInt("user_id"));
                order.setUser(user);

                return order;
            }
        }, userId);
        return orders;
    }

    @Override
    public Order selectDetailById(Integer id) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Order order = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = new StringBuffer()
                    .append(" select o.id,u.username,u.phone,o.no,i.id 'i.id',p.name,i.num,i.price 'i.price',o.price, ")
                    .append(" (select count(1) from t_item where order_id = o.id) count ")
                    .append(" from t_order o ")
                    .append(" left join t_user u ")
                    .append("     on o.user_id = u.id ")
                    .append(" left join t_item i ")
                    .append("     on o.id = i.order_id ")
                    .append(" left join t_product p ")
                    .append("     on i.product_id = p.id ")
                    .append(" where o.id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            rs = ps.executeQuery();
            while (rs.next()) {
                // 一方数据映射
                if (order == null) {
                    order = new Order();
                    order.setId(rs.getInt("id"));
                    order.setNo(rs.getString("no"));
                    order.setPrice(rs.getDouble("price"));
                    order.setCount(rs.getInt("count"));
                    User user = new User();
                    user.setUsername(rs.getString("username"));
                    user.setPhone(rs.getString("phone"));
                    order.setUser(user);
                }
                // 多方数据映射
                Item item = new Item();
                item.setId(rs.getInt("i.id"));
                item.setNum(rs.getInt("num"));
                item.setPrice(rs.getDouble("i.price"));
                Product product = new Product();
                product.setName(rs.getString("name"));
                item.setProduct(product);

                // 将多方数据加入到一方数据的集合属性中
                order.addItem(item);
            }
        } catch (SQLException e) {
            throw new DataAccessException("数据访问异常");
        }
        return order;
    }
}
